package com.mp.approvalreq.servlet.Attendance;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.LeaveRequestLite;
import com.mp.approvalreq.entity.LeaveTypeAndDuration;
import com.mp.approvalreq.servlet.AbstractServlet;
import com.mp.checkin.entity.ApprovalData;
import com.mp.checkin.entity.Data4Salary;
import com.mp.checkin.service.CheckInDataServicePrx;
import com.mp.user.entity.User;
import com.mp.user.service.UserServicePrx;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 批量获得全公司某月按请假类型归类的请假时长
 * 输入"{"companyId":"12","contacts:[1,2,3,4],"month":"2016-10"}"
 *
 * @author Administrator
 */
@WebServlet("/getLeaveRequestContentTimeLastCurrentMonthGroupByType")
public class GetLeaveRequestContentTimeLastCurrentMonthGroupByType extends AbstractServlet {

    private static final long serialVersionUID = -6524473373623928868L;

    private static final Logger logger = LoggerFactory.getLogger(GetLeaveRequestContentTimeLastCurrentMonthGroupByType.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        try {
            JSONObject jo = getInput(req);
            Integer companyId = jo.getInteger("companyId");
            String month = jo.getString("month");
            List<Integer> contactIds = JSONObject.parseArray(jo.getString("contacts"), Integer.class);

            UserServicePrx userServicePrx = ServantUtils.getObject(UserServicePrx.class);
            List<User> userList = userServicePrx.getUserBaseInfoListByContactIds(contactIds);
            if (Utils.isEmpty(userList)) {
                throw new RpcServerLogicalException(1, "用户不存在");
            }

            Map<Integer, Integer> idMap = getIdMap(userList);
            CheckInDataServicePrx checkInDataServicePrx = ServantUtils.getObject(CheckInDataServicePrx.class);
            List<Data4Salary> data4Salaries = checkInDataServicePrx.getCheckInDataForSalary(companyId, month);
            List<LeaveRequestLite> leaveRequestLites = new ArrayList<>();
            for (Data4Salary data4Salary : data4Salaries) {
                if (!idMap.containsKey(data4Salary.getCompanyInfoId())) {
                    continue;
                }
                List<ApprovalData> leaveDetails = data4Salary.getLeaveDetail();
                if (Utils.isEmpty(leaveDetails)) {
                    continue;
                }
                Integer contactId = idMap.get(data4Salary.getCompanyInfoId());
                LeaveRequestLite leaveRequestLite = new LeaveRequestLite();
                leaveRequestLite.setApplicant(contactId);
                leaveRequestLite.setCurrentMonth(month);
                Map<String, LeaveTypeAndDuration> map = new HashMap<>(leaveDetails.size());
                for (ApprovalData leaveDetail : leaveDetails) {
                    if (!map.containsKey(leaveDetail.getLeaveType())) {
                        LeaveTypeAndDuration duration = new LeaveTypeAndDuration();
                        duration.setLeaveType(leaveDetail.getLeaveType());
                        map.put(leaveDetail.getLeaveType(), duration);
                    }
                    LeaveTypeAndDuration duration = map.get(leaveDetail.getLeaveType());
                    duration.addDuration(leaveDetail.getValidTime());
                }
                leaveRequestLite.setLeaveTypeAndDuration(new ArrayList<>(map.values()));
                leaveRequestLites.add(leaveRequestLite);
            }

            printResult(resp, leaveRequestLites);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void printResult(HttpServletResponse resp, List<LeaveRequestLite> leaveRequestLites) throws IOException {
        JSONObject result = new JSONObject();
        result.put("result", "0");
        result.put("res_info", "获得成功");
        result.put("data", leaveRequestLites);
        logger.info(result.toJSONString());

        printJson(resp, result.toJSONString());
    }

    private Map<Integer, Integer> getIdMap(List<User> userList) {
        Map<Integer, Integer> map = new HashMap<>(userList.size());
        for (User user : userList) {
            map.put(user.getCompanyInfoId(), user.getContactId());
        }
        return map;
    }

    private JSONObject getInput(HttpServletRequest req) throws Throwable {
        String reqBody = getContent(req);
        logger.info("json参数值 {}", reqBody);

        JSONObject jsonObject = JSONObject.parseObject(reqBody);
        if (StringUtils.isEmpty(jsonObject.getString("month"))) {
            throw new RpcServerLogicalException(1, "无输入参数");
        }

        if (jsonObject.getIntValue("companyId") == 0) {
            throw new RpcServerLogicalException(1, "公司id不能为空");
        }

        return jsonObject;
    }
}
